package com.cindata

import com.cindata.dictionary.*

class Mortgage
{
    // 贷款编号
    String serialNumber

    EstateImportBatch batch
    //所属押品导入批次
    // Estate estate
    // 所属押品
    String externalId
    //外部ID 押品编号
    String contractNo
    //  贷款合同编号
    Date startDate
    //  放款日期
    BigDecimal loansEvaluateTotalPrice
    //  贷款评估总价
    BigDecimal loansEvaluatePrice
    //  贷款评估单价
    BigDecimal loansAmount
    //  贷款总金额
    BigDecimal ltv
    //  抵押率
    BigDecimal cltv
    //动态抵押率 （%）
    BigDecimal loansBalance
    //  贷款余额
    Date endDate
    // 最初贷款到期日期
    String mortgageeName
    //    抵押权人
    HouseTypeDict estateType
    //    房屋类型
    Account account
    //   受理机构网点
    String accountName
    //    受理网点名称
    Boolean isFirstHouse
    //    是否首套房
    BigDecimal downPaymentAmount
    //    首付金额
    BigDecimal publicFundLoansAmount
    //    公积金贷款金额
    BigDecimal bankLoansAmount
    //    商业贷款金额（元）
    String loansBankName
    //    放款银行名称（大行名）
    Integer loansDuration
    //    最初应还款期数（月）
    RepaymentModeDict starRepaymentMode
    //    最初还款方式
    Integer repaymentDate
    //    每月应还款日
    ForwardLoanStepDict forwardLoanStep
    //    提前放款步骤
    LoanMethodDict loanMethod
    //    放款方式
    RepaymentModeDict curRepaymentMode
    //    当前还款方式
    BigDecimal curNormalTotalCapital
    //    正常还款总本金（元）
    BigDecimal curInAdvanceTotalCapital
    //    提前还款总本金（元）
    BigDecimal curOverdueTotalCapital
    //    逾期还款总本金（元）
    BigDecimal curRecycleTotalCapital
    //    当前回收总本金（元）
    BigDecimal curRecycleTotalInterest
    //    当前回收总利息（不含罚息）（元）
    BigDecimal curRecycleTotalFine
    //    当前回收总罚息（元）
    Integer curHasPaymentTODuration
    //    当前已还款期数(含转逾期)（月）
    Integer curHasPaymentDuration
    //    当前已还款期数(不含转逾期)（月）
    Integer remainTime
    //    当前剩余还款期数（月）
    GuaranteeMethodDict guaranteeMethod
    //    担保方式
    Account guaranteeInstitution
    //    担保机构
    String borrPublicFundAccount
    //    主借款人公积金账号
    String borrName
    //    主借款人姓名
    String borrPhone
    //    主借款人联系电话
    String borrIdCardNo
    //    主借款人身份证号
    Date borrBirthday
    //    主借款人出身年月日
    AccountNatureDict borrAccountNature
    //    主借款人户口性质
    Integer borrOwnHouseCount
    //    主借款人家庭已购房套数
    String borrWorkUnitName
    //    主借款人工作单位名称
    OrganizationNatureDict borrWorkUnitNature
    //    主借款人工作单位性质
    DepositedStateDict borrDepositedState
    //    主借款人当前缴存状态
    BigDecimal borrDepositBaseOnLoans
    //    主借款人贷款时月缴存基数（元）
    BigDecimal borrDepositAmountOnLoans
    //    主借款人贷款时月缴存额（元）
    BigDecimal borrDepositBaseOnCurrent
    //    主借款人当前月缴存基数（元）
    BigDecimal borrDepositAmountOnCurrent
    //    主借款人当前月缴存额（元）
    BigDecimal borrFmiOnLoans
    //    主借款人贷款时家庭月收入（元）

    String borrAddress
    //    主借款人地址
    MortgageStatusDict mortgageStatus
    //    贷款状态
    Boolean isAntiFraud = false
    //    是否命中反欺诈

    RepaymentStateDict curRepaymentState
    //   当前贷款还款状态
    Integer curOverdueDuration
    //    当前逾期总期数
    Date lastPayAt
    //    最后扣款日期
    Date payOffAt
    //    最后还清时间
    Integer curDefaultingDuration
    //    当前违约总期数
    EvaluateDict evaluateType
    // 1:自动评估 2：人工评估

    ExecStatusDict evaluateStatue

    BigDecimal unitPrice
    BigDecimal totalPrice

    String evaluateCode

    Date createdDate = new Date()
    Date modifiedDate = new Date()
    User createBy
    User modifyBy

    RiskWarningStatusDict warningStatus
    RiskWarningDealTypeDict dealType

    // 贷后管理系统字段
    MortgagePattern mortgagePattern
    // 抵押模式 1.抵押 2.质押
    MortgageType mortgageType
    // 抵押类型 1.一抵 2.二抵 3.一抵转单 4.二抵转单
    MortgageCategory mortgageCategory
    // 企业贷， 小微贷， 零售贷
    Boolean isNonPerformingLoan = false
    // 是否是不良贷款

    // Vehicle vehicle
    // FinancialPledge financialPledge
    // AccountsReceivable accountsReceivable
    // OtherCollateral otherCollateral
    Collateral collateral

    Contact mortgageContact
    // 信用贷主借款人
    Account mortgageAccount
    // 企业贷企业

    RiskWarningLevel riskWarningLevel
    // 风险登记

    static belongsTo = [batch: EstateImportBatch]
    static hasMany = [contacts: MortgageContact, attachments: Attachment, contracts: MortgageContract]

    static constraints = {
        batch nullable: true, blank: true, comment: '所属押品导入批次'

        collateral nullable: true, blank: true, comment: '押品'

        // estate nullable: true, blank: true, comment: '所属房产押品'
        // vehicle nullable: true, blank: true, comment: '所属车辆类押品'
        // otherCollateral nullable: true, blank: true, comment: '所属其他抵质押品'
        // financialPledge nullable: true, blank: true, comment: '所属金融质押品类押品'
        // accountsReceivable nullable: true, blank: true, comment: '所属应收账款类押品'
        mortgageContact nullable: true, blank: true, comment: '信用贷借款人'
        mortgageAccount nullable: true, blank: true, comment: '企业贷企业'
        externalId maxSize: 128, nullable: true, blank: true, comment: '押品编号'
        contractNo maxSize: 64, nullable: true, blank: true, comment: '贷款合同编号'
        loansEvaluateTotalPrice nullable: true, blank: true, precision: 15, scale: 2, comment: '贷款评估总价'
        loansEvaluatePrice nullable: true, blank: true, precision: 15, scale: 2, comment: '贷款评估单价'
        loansAmount nullable: true, blank: true, precision: 15, scale: 2, comment: '贷款总金额'
        loansDuration nullable: true, blank: true, maxSize: 10, comment: '最初应还款期数（月）'
        loansBalance nullable: true, blank: true, precision: 15, scale: 2, comment: '贷款余额'
        startDate nullable: true, blank: true, comment: '放款日期'
        endDate nullable: true, blank: true, comment: '最初贷款到期日期'
        createdDate nullable: true, blank: true, comment: '创建日期'
        modifiedDate nullable: true, blank: true, comment: '修改日期'
        createBy nullable: true, blank: true, comment: '导入用户'
        modifyBy nullable: true, blank: true, comment: '修改用户'
        remainTime nullable: true, blank: true, comment: '当前剩余还款期数（月）'
        ltv precision: 5, scale: 4, nullable: true, blank: true, comment: '抵押率'
        cltv precision: 5, scale: 4, nullable: true, blank: true, comment: '动态抵押率'
        evaluateType nullable: true, blank: true, comment: '评估类型1:自动评估 2：人工评估'
        evaluateStatue nullable: true, blank: true, comment: '评估状态'
        evaluateCode nullable: true, blank: true, maxSize: 30, comment: '评估代码'
        unitPrice precision: 15, scale: 2, nullable: true, blank: true, comment: '房屋单价'
        totalPrice precision: 15, scale: 2, nullable: true, blank: true, comment: '房屋总价'

        mortgageeName maxSize: 100, nullable: true, blank: true, comment: '抵押权人'
        estateType nullable: true, blank: true, comment: '房屋类型'
        account nullable: true, blank: true, comment: '受理机构网点'
        accountName maxSize: 100, nullable: true, blank: true, comment: '受理网点名称'
        isFirstHouse nullable: true, blank: true, default: true, comment: '是否首套房'
        downPaymentAmount nullable: true, blank: true, precision: 15, scale: 2, comment: '首付金额'
        publicFundLoansAmount nullable: true, blank: true, precision: 15, scale: 2, comment: '公积金贷款金额'
        bankLoansAmount nullable: true, blank: true, precision: 15, scale: 2, comment: '商业贷款金额（元）'
        loansBankName maxSize: 100, nullable: true, blank: true, comment: '放款银行名称（大行名）'
        starRepaymentMode nullable: true, blank: true, comment: '最初还款方式'
        repaymentDate maxSize: 2, nullable: true, blank: true, comment: '每月还款日'
        forwardLoanStep nullable: true, blank: true, comment: '提前放款步骤'
        loanMethod nullable: true, blank: true, comment: '放款方式'
        curRepaymentMode nullable: true, blank: true, comment: '当前还款方式'
        curNormalTotalCapital nullable: true, blank: true, precision: 15, scale: 2, comment: '正常还款总本金（元）'
        curInAdvanceTotalCapital nullable: true, blank: true, precision: 15, scale: 2, comment: '提前还款总本金（元）'
        curOverdueTotalCapital nullable: true, blank: true, precision: 15, scale: 2, comment: '逾期还款总本金（元）'
        curRecycleTotalCapital nullable: true, blank: true, precision: 15, scale: 2, comment: '当前回收总本金（元）'
        curRecycleTotalInterest nullable: true, blank: true, precision: 15, scale: 2, comment: '当前回收总利息（不含罚息）（元）'
        curRecycleTotalFine nullable: true, blank: true, precision: 15, scale: 2, comment: '当前回收总罚息（元）'
        curHasPaymentTODuration maxSize: 4, nullable: true, blank: true, comment: '当前已还款期数(含转逾期)（月）'
        curHasPaymentDuration maxSize: 4, nullable: true, blank: true, comment: '当前已还款期数(不含转逾期)（月）'
        guaranteeMethod nullable: true, blank: true, comment: '担保方式'
        guaranteeInstitution maxSize: 100, nullable: true, blank: true, comment: '担保机构'
        borrPublicFundAccount maxSize: 50, nullable: true, blank: true, comment: '主借款人公积金账号'
        borrName maxSize: 50, nullable: true, blank: true, comment: '主借款人姓名'
        borrPhone maxSize: 20, nullable: true, blank: true, comment: '主借款人联系电话'
        borrIdCardNo maxSize: 20, nullable: true, blank: true, comment: '主借款人身份证号'
        borrBirthday nullable: true, blank: true, comment: '主借款人出身年月日'
        borrAccountNature nullable: true, blank: true, comment: '主借款人户口性质'
        borrOwnHouseCount maxSize: 8, nullable: true, blank: true, comment: '主借款人家庭已购房套数'
        borrWorkUnitName maxSize: 100, nullable: true, blank: true, comment: '主借款人工作单位名称'
        borrWorkUnitNature nullable: true, blank: true, comment: '主借款人工作单位性质'
        borrDepositedState nullable: true, blank: true, comment: '主借款人当前缴存状态'
        borrDepositBaseOnLoans nullable: true, blank: true, precision: 15, scale: 2, comment: '主借款人贷款时月缴存基数（元）'
        borrDepositAmountOnLoans nullable: true, blank: true, precision: 15, scale: 2, comment: '主借款人贷款时月缴存额（元）'
        borrDepositBaseOnCurrent nullable: true, blank: true, precision: 15, scale: 2, comment: '主借款人当前月缴存基数（元）'
        borrDepositAmountOnCurrent nullable: true, blank: true, precision: 15, scale: 2, comment: '主借款人当前月缴存额（元）'
        borrFmiOnLoans nullable: true, blank: true, precision: 15, scale: 2, comment: '主借款人贷款时家庭月收入（元）'
        curRepaymentState nullable: true, blank: true, comment: '当前贷款还款状态'
        curOverdueDuration maxSize: 4, nullable: true, blank: true, comment: '当前逾期数（月）'
        curDefaultingDuration maxSize: 4, nullable: true, blank: true, comment: '当前违约数'
        lastPayAt nullable: true, blank: true, comment: '最后扣款日期'
        payOffAt nullable: true, blank: true, comment: '最后还清时间'

        borrAddress nullable: true, blank: true, comment: '主借款人地址'
        mortgageStatus nullable: true, blank: true, comment: '贷款状态'
        isAntiFraud nullable: true, blank: true, comment: '是否命中反欺诈'

        warningStatus nullable: true, blank: true, comment: '预警状态'
        dealType nullable: true, blank: true, comment: '预警类型'

        mortgagePattern nullable: true, blank: true
        mortgageType nullable: true, blank: true
        mortgageCategory nullable: true, blank: true
        isNonPerformingLoan nullable: true, blank: true

        serialNumber nullable: true, blank: true
        riskWarningLevel nullable: true, blank: true
    }

    // 同步房贷数据
    static CreateFromEstate(Estate fromEstate)
    {
        if (!fromEstate)
        {
            return
        }
        def estateImport = EstateImport.findByExternalId(fromEstate.externalId)
        def mortgage = Mortgage.CreateFromEstateImport(estateImport)
        if (mortgage)
        {
            // mortgage.estate = fromEstate
            mortgage.cltv = fromEstate.cltv
            mortgage.save()
        }
        return mortgage
    }

    // 同步房贷数据
    static CreateFromEstateImport(EstateImport ei)
    {
        if (!ei)
        {
            return
        }

        def mortgage = Mortgage.findByContractNo(ei.contractNo)
        if (!mortgage)
        {
            mortgage = new Mortgage()
            mortgage.batch = ei.batch
            mortgage.contractNo = ei.contractNo
            mortgage.externalId = ei.externalId
            mortgage.createdDate = ei.createdDate
            mortgage.createBy = ei.createBy
        }
        mortgage.unitPrice = ei.unitPrice
        mortgage.totalPrice = ei.totalPrice
        mortgage.ltv = ei.ltv
        mortgage.mortgageeName = ei.mortgageeName
        mortgage.estateType = ei.estateType
        mortgage.accountName = ei.accountName
        mortgage.isFirstHouse = ei.isFirstHouse
        mortgage.downPaymentAmount = ei.downPaymentAmount
        mortgage.publicFundLoansAmount = ei.publicFundLoansAmount
        mortgage.bankLoansAmount = ei.bankLoansAmount
        mortgage.loansBankName = ei.loansBankName
        mortgage.starRepaymentMode = ei.starRepaymentMode
        mortgage.repaymentDate = ei.repaymentDate
        mortgage.forwardLoanStep = ei.forwardLoanStep
        mortgage.loanMethod = ei.loanMethod
        mortgage.curRepaymentMode = ei.curRepaymentMode
        mortgage.curRecycleTotalCapital = ei.curRecycleTotalCapital
        mortgage.curRecycleTotalInterest = ei.curRecycleTotalInterest
        mortgage.curRecycleTotalFine = ei.curRecycleTotalFine
        mortgage.curHasPaymentTODuration = ei.curHasPaymentTODuration
        mortgage.curHasPaymentDuration = ei.curHasPaymentDuration
        mortgage.guaranteeMethod = ei.guaranteeMethod
        mortgage.guaranteeInstitution = ei.guaranteeInstitution
        mortgage.borrPublicFundAccount = ei.borrPublicFundAccount
        mortgage.borrName = ei.borrName
        mortgage.borrPhone = ei.borrPhone
        mortgage.borrIdCardNo = ei.borrIdCardNo
        mortgage.borrBirthday = ei.borrBirthday
        mortgage.borrAccountNature = ei.borrAccountNature
        mortgage.borrOwnHouseCount = ei.borrOwnHouseCount
        mortgage.borrWorkUnitName = ei.borrWorkUnitName
        mortgage.borrWorkUnitNature = ei.borrWorkUnitNature
        mortgage.borrDepositedState = ei.borrDepositedState
        mortgage.borrDepositBaseOnLoans = ei.borrDepositBaseOnLoans
        mortgage.borrDepositAmountOnLoans = ei.borrDepositAmountOnLoans
        mortgage.borrDepositBaseOnCurrent = ei.borrDepositBaseOnCurrent
        mortgage.borrDepositAmountOnCurrent = ei.borrDepositAmountOnCurrent
        mortgage.borrFmiOnLoans = ei.borrFmiOnLoans
        mortgage.borrAddress = ei.address
        mortgage.mortgageCategory = MortgageCategory.findByCode("1")

        mortgage.save()


        def contact = Contact.findByIdNumberOrCellphone(ei.borrIdCardNo, ei.borrPhone)
        if (!contact)
        {
            contact = new Contact()
        }
        // contact.mortgage = mortgage
        contact.type = ContactType.findByCode("1")
        contact.fullName = ei.borrName
        contact.cellphone = ei.borrPhone
        contact.identityType = ContactIdentityType.findByName('身份证')
        contact.idNumber = ei.borrIdCardNo
        contact.birthday = ei.borrBirthday
        contact.accountNature = ei.borrAccountNature
        contact.ownHouseCount = ei.borrOwnHouseCount
        contact.workUnitName = ei.borrWorkUnitName
        contact.workUnitNature = ei.borrWorkUnitNature
        contact.depositedState = ei.borrDepositedState
        contact.depositBaseOnLoans = ei.borrDepositBaseOnLoans
        contact.depositAmountOnLoans = ei.borrDepositAmountOnLoans
        contact.depositBaseOnCurrent = ei.borrDepositBaseOnCurrent
        contact.depositAmountOnCurrent = ei.borrDepositAmountOnCurrent
        contact.fmiOnLoans = ei.borrFmiOnLoans
        contact.address = ei.address
        contact.publicFundAccount = ei.borrPublicFundAccount
        if (contact.validate())
        {
            contact.save()
        }
        else
        {
            println contact.errors
        }

        def mortgageContact = MortgageContact.findByMortgageAndContactAndType(mortgage, contact, ContactType.findByCode("1"))
        if (!mortgageContact)
        {
            mortgageContact = new MortgageContact()
        }
        mortgageContact.mortgage = mortgage
        mortgageContact.contact = contact
        mortgageContact.type = ContactType.findByCode("1")
        if (mortgageContact.validate())
        {
            mortgageContact.save()
        }
        else
        {
            println mortgageContact.errors
        }
        return mortgage
    }

    def springSecurityService

    def beforeUpdate()
    {
        modifiedDate = new Date()
        def username = springSecurityService?.getPrincipal()?.username
        modifyBy = User.findByUsername(username)
    }
}
